package com.xwj.service.Impl;

import com.xwj.dao.RaRoleRootDao;
import com.xwj.entity.RaRoleRoot;
import com.xwj.service.Interface.RaRoleRootService;
import com.xwj.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by thinkjoy on 2017/7/12.
 */
@Slf4j
@Service
@CacheConfig(cacheNames = "RaRoleRootCache")
public class RaRoleRootServiceImpl implements RaRoleRootService {

    @Autowired
    private RaRoleRootDao raRoleRootDao;

    public static RaRoleRootServiceImpl getInstance() {
        return SpringUtils.getBean(RaRoleRootServiceImpl.class);
    }

    @Override
    @Cacheable(key = "#root.methodName")
    public List<RaRoleRoot> findAllRoleRoot() {
        return raRoleRootDao.findAllRoleRoot();
    }

    @Override
    @Cacheable(key = "#root.methodName + #roleid")
    public List<RaRoleRoot> findRoleRootByRoleId(int roleid) {
        try {
            return raRoleRootDao.findRoleRootByRoleId(roleid);
        } catch (NullPointerException e) {
            log.error("RaRoleRootService异常:", e);
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    @Override
    @Cacheable(key = "#root.methodName")
    public List<RaRoleRoot> findRoleRootByRoleIds(List roleids) {
        return raRoleRootDao.findRoleRootByRoleIds(roleids);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int deleteAllRoot(int roleId) {
        try {
            return raRoleRootDao.deleteAllRoot(roleId);
        } catch (Exception e) {
            log.error("RaRoleRootService异常:", e);
            return 0;
        }
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int deleteRootById(Map<String, Object> map) {
        return raRoleRootDao.deleteRootById(map);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int insertRoleRoot(Map<String, Object> map) {
        deleteAllRoot((Integer) map.get("roleId"));
        return raRoleRootDao.insertRoleRoot(map);
    }

    @Override
    @Cacheable(key = "#root.methodName+'_root_'+#id")
    public List<RaRoleRoot> findRoleByRootId(int id) {
        try {
            return raRoleRootDao.findRoleByRootId(id);
        } catch (Exception e) {
            log.error("RaRoleRootService异常:", e);
            return Collections.emptyList();
        }

    }
}
